package com.vipheyue.bigbusiness.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bmob.BTPFileResponse;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.LocalThumbnailListener;
import com.bmob.btp.callback.UploadListener;
import com.lidroid.xutils.util.LogUtils;
import com.vipheyue.bigbusiness.R;
import com.vipheyue.bigbusiness.bean.Company;
import com.vipheyue.bigbusiness.bean.Job;
import com.vipheyue.bigbusiness.utils.UriConfig;
import com.vipheyue.bigbusiness.view.CustomDialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.SaveListener;

public class ReleaseActivity extends Activity {

    @Bind(R.id.tv_pick_img)
    TextView tv_pick_img;
    @Bind(R.id.iv_logo)
    ImageView iv_logo;
    @Bind(R.id.et_JobTitle)
    EditText et_JobTitle;
    @Bind(R.id.et_JobType)
    EditText et_JobType;
    @Bind(R.id.et_WorkAreaType)
    EditText et_WorkAreaType;
    @Bind(R.id.et_MaxSalary)
    EditText et_MaxSalary;
    @Bind(R.id.et_SalaryType)
    EditText et_SalaryType;
    @Bind(R.id.et_WorkAddressDetail)
    EditText et_WorkAddressDetail;
    @Bind(R.id.et_JobRebate)
    EditText et_JobRebate;
    @Bind(R.id.bt_JobWelfare)
    Button bt_JobWelfare;
    @Bind(R.id.et_ContactsPeople)
    EditText et_ContactsPeople;
    @Bind(R.id.et_ContactsPhone)
    EditText et_ContactsPhone;
    @Bind(R.id.et_DetailDescription)
    EditText et_DetailDescription;
    @Bind(R.id.et_company)
    EditText et_company;
    @Bind(R.id.tv_comany_description)
    EditText tv_comany_description;
    @Bind(R.id.bt_commit)
    Button bt_commit;
    private static final int CAMERA_WITH_DATA = 3023;
    private static final int REQUEST_CODE_PICK_IMAGE=3033;
    private Dialog dialog;
    private BmobFile successImgFile=null;
    private static final int JobWelfareListActivity_Result=3334;
    private ArrayList<String> search_jobWelfare_list;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release);
        ButterKnife.bind(this);
    }

    protected void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");//相片类型
            startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) return;

        switch (requestCode) {
            case REQUEST_CODE_PICK_IMAGE:
                Uri uri = data.getData();
                Bitmap bm = null;
                ContentResolver resolver = getContentResolver();
                try {
                    Uri originalUri = data.getData();        //获得图片的uri
                    bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);        //显得到bitmap图片
//                        这里开始的第二部分，获取图片的路径：
                    String[] proj = {MediaStore.Images.Media.DATA};
                    //好像是android多媒体数据库的封装接口，具体的看Android文档
                    Cursor cursor = managedQuery(originalUri, proj, null, null, null);
                    //按我个人理解 这个是获得用户选择的图片的索引值
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    //将光标移至开头 ，这个很重要，不小心很容易引起越界
                    cursor.moveToFirst();
                    //最后根据索引值获取图片路径
                    String path = cursor.getString(column_index);
                    File file = new File(path);
                    LogUtils.i("path=---file->"+file.length());
                    LogUtils.i("path=---->"+path);
                    createLocalSmartImg(file.getAbsolutePath());
                    dialog = CustomDialog.onCreateDialog(ReleaseActivity.this);
                }catch (IOException e) {
//                        Log.e(TAG,e.toString());
                }
                break;
            case CAMERA_WITH_DATA:

                if (resultCode == Activity.RESULT_OK && null != data) {
                    String sdState = Environment.getExternalStorageState();
                    if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                        return;
                    }
                    Bundle bundle = data.getExtras();
                    //获取相机返回的数据，并转换为图片格式
                    Bitmap bitmap = (Bitmap) bundle.get("data");
                    FileOutputStream fout = null;
                    File file = new File(getCacheDir(), "cropped.jpg");
                    String filename = file.getAbsolutePath();
                    try {
                        fout = new FileOutputStream(filename);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            fout.flush();
                            fout.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    LogUtils.i("---->" + file.length());

                    //显示图片
//                    iv_logo.setImageBitmap(bitmap);
//                    saveAndUpdate(filename);
                }
                break;
            case JobWelfareListActivity_Result:
                search_jobWelfare_list = data.getStringArrayListExtra("search_jobWelfare_list");
                break;


        }
    }
    public void createLocalSmartImg(String absolutePath){
        BmobProFile.getInstance(this).getLocalThumbnail(absolutePath, 1, new LocalThumbnailListener() {

            @Override
            public void onError(int statuscode, String errormsg) {
                // TODO Auto-generated method stub
                Log.i("bmob","localThumbnail-->生成缩略图失败 :"+statuscode+","+errormsg);
                Toast.makeText(ReleaseActivity.this, "图片格式不支持", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(String thumbnailPath) {
                // TODO Auto-generated method stub
                Log.i("bmob", "localThumbnail-->生成后的缩略图路径 :" + thumbnailPath);
                LogUtils.i("path=---file生成后的缩略图路径 :->" + thumbnailPath);
                iv_logo.setImageBitmap(BitmapFactory.decodeFile(thumbnailPath));
                uploadImg(thumbnailPath);


            }
        });
    }
    private void uploadImg(String filePath) {

        BTPFileResponse response = BmobProFile.getInstance(this).upload(filePath, new UploadListener() {

            @Override
            public void onSuccess(String fileName, String url, BmobFile file) {
                Log.i("bmob", "文件上传成功：" + fileName + ",可访问的文件地址：" + file.getUrl());
                /***************************************/
                successImgFile = file;
                dialog.dismiss();
                Toast.makeText(ReleaseActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                /***************************************/
            }

            @Override
            public void onProgress(int progress) {
                // TODO Auto-generated method stub
                Log.i("bmob", "onProgress :" + progress);
            }

            @Override
            public void onError(int statuscode, String errormsg) {
                // TODO Auto-generated method stub
                Log.i("bmob", "文件上传失败：" + errormsg);
                Toast.makeText(ReleaseActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
            }
        });

    }
    @OnClick({R.id.tv_pick_img, R.id.bt_commit,R.id.bt_JobWelfare})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_pick_img:
                getImageFromCamera();
                break;
            case R.id.bt_JobWelfare:
                startActivityForResult(new Intent(this, JobWelfareListActivity.class), JobWelfareListActivity_Result);
                break;
            case R.id.bt_commit:
                dialog = CustomDialog.onCreateDialog(ReleaseActivity.this);
                bt_commit.setClickable(false);
                commmitinfo();
                break;
        }
    }

    private void commmitinfo() {
//        if(successImgFile==null) {
//            Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show();
//            bt_commit.setClickable(true);
//            return;
//        }
        Job job = new Job();
        Company company = new Company();
        company.setObjectId(UriConfig.releaseCompanyId);
        job.setPublisherCompany(company);
        job.setJobTitle(et_JobTitle.getText().toString());
        job.setJobType(et_JobType.getText().toString());
        job.setPartTimeJob(true);
        job.setWorkAreaType(et_WorkAreaType.getText().toString());
        job.setWorkAddressDetail(et_WorkAddressDetail.getText().toString());
        job.setEducationLevel("本科");
//        job.setMinSalary(5000);
        job.setMaxSalary(et_MaxSalary.getText().toString());
        job.setContactsPeople(et_ContactsPeople.getText().toString());
        job.setSalaryType(et_SalaryType.getText().toString());
        job.setWorkDay("周末");
        job.setContactsPhone(et_ContactsPhone.getText().toString());
        job.setDetailDescription(et_DetailDescription.getText().toString());
        job.setJobRebate(et_JobRebate.getText().toString());
        if (search_jobWelfare_list == null||search_jobWelfare_list.size()==0) {
                        Toast.makeText(this, "请选择福利待遇", Toast.LENGTH_SHORT).show();
            return;
        }
        job.setJobWelfareList(search_jobWelfare_list);
        job.setAgeLimit("18-40岁");
        job.setIsMale(true);

        job.setCompanyLogo(successImgFile);
        job.setCompanyDescription(tv_comany_description.getText().toString());
        job.setCompanyName(et_company.getText().toString());

        job.setDisplay(true);
        job.save(ReleaseActivity.this, new SaveListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(ReleaseActivity.this, "发布成功", Toast.LENGTH_LONG).show();
                LogUtils.i("发布成功");
                dialog.dismiss();
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(ReleaseActivity.this, "发布失败" + s, Toast.LENGTH_LONG).show();
                LogUtils.i("发布失败" + s);
                bt_commit.setClickable(true);
                dialog.dismiss();
            }
        });
    }


}
